
const gulp = require("gulp");
const ts = require("gulp-typescript");
const sourcemaps = require('gulp-sourcemaps');
const uglify = require("gulp-uglify");
const clean = require('gulp-clean');
const jsobfuscator = require('gulp-javascript-obfuscator');
const debug = require('gulp-debug');
const merge = require('merge2');
const through = require('through2');
const fs = require("fs");
const path = require("path");
const yargs = require('yargs');

/**
 * 清空框架
 */
function cleanFramework(cb) {
	if(fs.existsSync('src')){
		console.log("cleanFramework");
		return gulp.src([ 'dist/lcc-framework.js', 'dist/lcc-framework.d.ts', 'dist/lcc-framework.js.map' ], { read: false, allowEmpty:true })
			.pipe(clean({ force:true }));
	}else{
		console.error("src not found!");
		cb();
	}
}

/**
 * 构建框架
 */
function buildFramework(cb) {
	if(fs.existsSync('src')){
		console.log("buildFramework");
		let tsResult = gulp.src([ 'src/**/*.ts' ])
			.pipe(sourcemaps.init())
            .pipe(ts.createProject('src/tsconfig.json')())
			.on("error",function(err:any){
				console.error(err.message);
			});
		return merge(
			tsResult.js
				/*
				.pipe(jsobfuscator({
					compact: true
				}))
				.pipe(uglify())
				*/
				.pipe(sourcemaps.write())
				.pipe(gulp.dest('dist')),
			tsResult.dts
				/*
				.pipe(rename((path)=>{
					path.basename = "lcc-" + path.basename; 
				}))
                */
			    /*
                .pipe(through.obj(function (chunk, enc, callback){
                    let sdata = chunk.contents.toString();
                    //sdata = sdata.replace(new RegExp('/// <reference types="../../../../temp', "g" ),'/// <reference types="../../temp');
                    chunk.contents = Buffer.from(sdata);
                    this.push(chunk)
                    callback();
                }))
				*/
				.pipe(gulp.dest('dist'))
			);
	}else{
		console.error("src not found!");
		cb();
	}
}

export const build = gulp.series(cleanFramework, buildFramework);
